/**
 * 高亮插件，普通jQuery版
 * Author: 陆楚良
 * Version: 1.0.0
 * Date: 2014-04-12
 * QQ: 519998338
 *
 * https://git.oschina.net/luchg/jquery.highlight.js.git
 *
 * License: http://www.apache.org/licenses/LICENSE-2.0
 **/
/*
用法：
	$(".selector").highlight("classname", "href");
*/
(function($){
	//className-高亮样式名，attrName-元素属性名(缺省href)
	$.fn.highlight = function(className, attrName){
		var attrName = attrName || "href";
		var self = this;
		var f = function(){
			var top = $(document).scrollTop();
			var bottom=$(document).scrollTop()+$(window).height();
			var list = [];
			self.each(function(){
				var h = $(this).attr(attrName);
				if(h==="#"){
					list.push({top:0, bottom:0});
				}
				else if(/^#.+/.test(h)){
					var o = $(h).offset();
					o= (typeof o == "object") ? o : {top:0};
					list.push({top:o.top, bottom:o.top+Number($(h).height())});
				}
			});
			self.removeClass(className);
			for(var i=0;i<list.length; i++){
				if(list[i].top>=top && list[i].top<=bottom && list[i].bottom<=bottom){//包含
					self.removeClass(className).eq(i).addClass(className);
					break;//第一个包含的内容以第一个为当前高亮 00
				}else{
					if(
						(list[i].top>=top && list[i].top<=bottom)// 露头
						|| (list[i].bottom>=top && list[i].bottom<=bottom)// 露尾
						|| (list[i].top<=top && list[i].bottom>=bottom)// 局部
					){
						self.removeClass(className).eq(i).addClass(className);
					}
				}
			}
		};
		$(window).scroll(f);
		f();
		return this;	/*return this使其可以连贯操作*/
	}
})(jQuery);